package com.jack.xiaoer.web.controller;

import com.jack.xiaoer.constant.OrderStateEnum;
import com.jack.xiaoer.dto.CartDTO;
import com.jack.xiaoer.dto.OrderDTO;
import com.jack.xiaoer.dto.OrderDetailDTO;
import com.jack.xiaoer.entity.Order;
import com.jack.xiaoer.service.OrderService;
import com.jack.xiaoer.util.AjaxResponse;
import com.jack.xiaoer.validator.Groups;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/19.
 */
@Validated
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public AjaxResponse create(@RequestBody @Validated({Groups.OrderCreate.class}) Optional<OrderDTO> orderDTOOptional
            , BindingResult bindingResult) {
        AjaxResponse error = commonValidate(orderDTOOptional, bindingResult);
        if (null != error) {
            return error;
        }

        Order order = orderService.create(orderDTOOptional);
        if (order == null) {
            return AjaxResponse.fail("创建订单失败");
        }

        return AjaxResponse.success("创建订单成功", order);
    }

    @GetMapping("/detail/{orderId}")
    public AjaxResponse detail(@PathVariable Long orderId) {

        OrderDetailDTO orderDetailDTO = orderService.getOrderDetail(orderId);
        if (orderDetailDTO == null) {
            return AjaxResponse.fail("获取订单详情失败");
        }

        return AjaxResponse.success("获取订单详情成功", orderDetailDTO);
    }

    @GetMapping("/list/{userId}/{stateCode}")
    public AjaxResponse list(@PathVariable Long userId, @PathVariable Integer stateCode) {
        if (!OrderStateEnum.valid(stateCode)) {
            return AjaxResponse.invalid("订单状态参数错误");
        }

        List<Order> orders = orderService.listByUserIdAndState(userId, stateCode);

        return AjaxResponse.success("获取订单列表成功", orders);
    }



}
